from django.shortcuts import render
from django.views import View
from django.http import JsonResponse
from order.models import Order
from ihome.utils.views import LoginRequiredJsonMixin
from homes.models import House
import json, logging, datetime

logger = logging.getLogger('ihome')
url = "http://qs930d3tn.hn-bkt.clouddn.com/"


class CreateOrderView(LoginRequiredJsonMixin, View):
    """订单"""

    # 创建订单
    def post(self, request):
        # 1、接收参数
        user = request.user
        json_dict = json.loads(request.body.decode("utf-8"))
        house_id = json_dict.get("house_id")
        start_date_str = json_dict.get("start_date")
        end_date_str = json_dict.get("end_date")

        # 2、校验参数
        if not all([house_id, start_date_str, end_date_str]):
            return JsonResponse({'errno': 4002, 'errmsg': '缺少必传参数'})
        try:
            house_model = House.objects.get(id=house_id)
        except Exception as e:
            logging.error(e)
            return JsonResponse({'errno': 4004, 'errmsg': 'house_id参数有误'})

        # 3、业务处理
        # 3.1 判断用户租住天数是否符合房源最小和最大租住天数要求
        start_date = datetime.date(*map(int, start_date_str.split('-')))
        end_date = datetime.date(*map(int, end_date_str.split('-')))
        day = (end_date - start_date).days
        if day < house_model.min_days:
            return JsonResponse({"errno": 4004, "errmsg": "租住天数太少"})
        elif house_model.max_days != 0:
            if day > house_model.max_days:
                return JsonResponse({"errno": 4004, "errmsg": "租住天数太多"})

        # 3.2 创建订单表
        order_model = Order.objects.create(
            user=user,
            house=house_model,
            begin_date=start_date,
            end_date=end_date,
            days=day,
            house_price=house_model.price,
            amount=day * house_model.price
        )

        # 4、响应返回
        return JsonResponse({"errno": 0, "errmsg": "下单成功", "data": {"order_id": order_model.id}})

    # 获取订单列表
    def get(self, request):
        # 1、获取参数
        user = request.user
        role = request.GET.get("role")

        # 2、校验参数
        if role is None:
            return JsonResponse({'errno': 4002, 'errmsg': '缺少必传参数'})

        # 3、业务处理
        if role == "custom":        # 房客
            orders_model = Order.objects.filter(user_id=user.id).order_by("-create_time")
        elif role == "landlord":    # 房东
            houses_model = user.houses.all()
            houses_id = [house_model.id for house_model in houses_model]
            orders_model = Order.objects.filter(house_id__in=houses_id).order_by("-create_time")
        else:
            return JsonResponse({'errno': 4004, 'errmsg': 'role参数有误'})

        # 4、响应返回
        orders = []
        for order_model in orders_model:
            orders.append({
                "amount": order_model.amount,
                "comment": order_model.comment,
                "ctime": order_model.create_time.strftime("%Y-%m-%d"),
                "days": order_model.days,
                "start_date": order_model.begin_date.strftime("%Y-%m-%d"),
                "end_date": order_model.end_date.strftime("%Y-%m-%d"),
                "img_url": url + str(order_model.house.index_image_url),
                "order_id": order_model.id,
                "status": order_model.ORDER_STATUS_ENUM[order_model.status],
                "title": order_model.house.title
            })
        return JsonResponse({"errno": 0, "errmsg": "获取订单列表成功", "data": {"orders": orders}})


class SignOrdersView(LoginRequiredJsonMixin, View):
    """房东接单或拒单"""

    def put(self, request, order_id):
        # 1、获取参数
        json_dict = json.loads(request.body.decode("utf-8"))
        action = json_dict.get("action")
        reason = json_dict.get("reason")

        # 2、校验参数
        if action is None:
            return JsonResponse({'errno': 4002, 'errmsg': '缺少必传参数'})
        if action not in ["accept", "reject"]:
            return JsonResponse({'errno': 4004, 'errmsg': 'action参数有误'})
        if action == "reject":
            # 断言，如果reason为空则抛出异常
            assert reason, Exception("拒单时需传入拒单原因")

        # 3、业务处理
        try:
            if action == "accept":
                Order.objects.filter(id=order_id).update(status=3)
            else:
                Order.objects.filter(id=order_id).update(status=6, comment=reason)
        except Exception as e:
            logging.error(e)
            return JsonResponse({"errno": 4004, "errmsg": "操作失败"})

        # 4、响应返回
        return JsonResponse({"errno": 0, "errmsg": "操作成功"})


class AppraiseOrderView(View):
    """评价订单"""

    def put(self, request, order_id):
        # 1、获取参数
        json_dict = json.loads(request.body.decode("utf-8"))
        comment = json_dict.get("comment")

        # 2、校验参数
        if not all([comment, order_id]):
            return JsonResponse({'errno': 4002, 'errmsg': '缺少必传参数'})

        # 3、业务处理
        try:
            order_model = Order.objects.get(id=order_id)
            order_model.comment = comment
            order_model.status = 4
            order_model.save()
        except Exception as e:
            logging.error(e)
            return JsonResponse({'errno': 4004, 'errmsg': '评论失败'})

        # 4、响应返回
        return JsonResponse({"errno": 0, "errmsg": "评论成功"})
